package utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;

public class SoftFileLock {

	/**
	 * 文件锁路径
	 */
	private String lockFilePath;

	private File lockFile;

	public SoftFileLock() {
		lockFilePath = System.getProperty("user.home") + File.separator
				+ ".live_forest.lck";
		lockFile = new File(lockFilePath);
		if (!lockFile.exists()) {
			try {
				lockFile.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 加锁
	 *
	 * @return
	 */
	@SuppressWarnings("resource")
	public boolean lock() {
		try {
			RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile,
					"rw");
			FileChannel fileChannel = randomAccessFile.getChannel();
			FileLock fileLock = fileChannel.tryLock();
			if (fileLock != null) {
				return true;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OverlappingFileLockException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 确认是否已经启动了程序
	 *
	 * @return
	 */
	public static boolean isLocked() {
		SoftFileLock softFileLock = new SoftFileLock();
		return softFileLock.lock();
	}

	public String getLockFilePath() {
		return lockFilePath;
	}

	public void setLockFilePath(String lockFilePath) {
		this.lockFilePath = lockFilePath;
	}

	public File getLockFile() {
		return lockFile;
	}

	public void setLockFile(File lockFile) {
		this.lockFile = lockFile;
	}

}
